/*************************************************************
 * Title: Operation.java
 * Description: 
 * Author: Huang Shaobin
 * Email: huangshaobin@qtt.cn
 * CreateTime: Feb 6, 2013 4:38:18 PM
 * Copyright © 北京全天通信息咨询服务有限公司 All right reserved
 ************************************************************/
package snow.biz.security.model;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;

import snow.biz.base.model.BaseEntity;
import snow.biz.system.model.User;
import snow.core.enums.Status;
import snow.core.security.OperationType;
import snow.core.security.SecurityHelper;

/**
 *
 */
public class Operation extends BaseEntity<Integer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7227638891999239255L;

	private Integer value;

	protected Operation() {
		super();
	}

	public Operation(User createUser, Status status, Collection<OperationType> operationTypes) {
		super(createUser, status);
		if (CollectionUtils.isNotEmpty(operationTypes)) {
			Set<OperationType> set = new HashSet<OperationType>(operationTypes);
			for (OperationType operationType : set) {
				addOperationTypeFrom(operationType);
			}
		}
	}

	public Operation(User createUser, Status status, OperationType operationType) {
		this(createUser, status, Arrays.asList(new OperationType[] { operationType }));
	}

	public boolean addOperationTypeFrom(OperationType operationType) {
		if (operationType == null) {
			return false;
		}
		final int value = this.value == null || this.value.intValue() < 0 ? 0 : this.value.intValue();
		if (SecurityHelper.hasPermission(value, operationType.getValue())) {
			return false;
		}
		this.value = Integer.valueOf(value + operationType.getValue());
		return true;
	}

	public Integer getValue() {
		return value;
	}

}
